package com.tjec.project.system.controller;

import com.tjec.common.constant.Constants;
import com.tjec.common.constant.UserConstants;
import com.tjec.common.enums.NumCode;
import com.tjec.common.enums.UserStatus;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.common.utils.poi.CommonExcelUtil;
import com.tjec.common.utils.poi.ExcelUtil;
import com.tjec.framework.aspectj.lang.annotation.Log;
import com.tjec.framework.aspectj.lang.enums.BusinessType;
import com.tjec.framework.security.LoginUser;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.framework.web.page.TableDataInfo;
import com.tjec.project.system.domain.SysDept;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.service.IBmsMdBusinessCategoryService;
import com.tjec.project.system.service.ISysDeptService;
import com.tjec.project.system.service.ISysPostService;
import com.tjec.project.system.service.ISysRoleService;
import com.tjec.project.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Set;

/**
 * 用户管理
 *
 * @author tjec
 */
@Api(value= "用户管理", tags = {"用户管理接口"})
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;
    
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private IBmsMdBusinessCategoryService businessCategoryService;

    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取所有用户列表
     */
    @ApiOperation("获取所有用户列表")
    @GetMapping("/allList")
    public AjaxResult allList(SysUser user) {
        user.setUserType(NumCode.ZERO.getCode() + NumCode.ONE.getCode());
        user.setStatus(UserStatus.OK.getCode());
        user.setDelFlag(NumCode.ZERO.getCode());
        List<SysUser> list = userService.selectUserList(user);
        return AjaxResult.success(list);
    }

    @Log(title = "用户管理导出", businessType = BusinessType.EXPORT)
    //@PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户管理数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUser().getUserId();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("获取用户信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) String userId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("roles", roleService.selectRoleAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
            //部技术负责人
            SysDept dept1 = new SysDept();
            dept1.setTechLeader(userId);
            ajax.put("deptIds",deptService.selectDeptIds(dept1));
            
            //所技术负责人
            SysDept dept11 = new SysDept();
            dept11.setWhatBusinessTechLeader(userId);
            ajax.put("instituteDeptIds",deptService.selectDeptIds(dept11));
            
            //专业技术负责人
            ajax.put("businessTypeIds",businessCategoryService.selectBusinessIds(userId));
            
            //公章管理员
            SysDept dept2 = new SysDept();
            dept2.setCachetManage(userId);
            ajax.put("cachetDeptIds",deptService.selectDeptIds(dept2));
            
            //业务分管副总
            SysDept dept3 = new SysDept();
            dept3.setDeputyDir(userId);
            ajax.put("businessDeptIds",deptService.selectDeptIds(dept3));
            
            //部领导
            SysDept dept4 = new SysDept();
            dept4.setLeader(userId);
            ajax.put("deptLeaderIds",deptService.selectDeptIds(dept4));
            
            //所领导
            SysDept dept41 = new SysDept();
            dept41.setWhatBusinessLeader(userId);
            ajax.put("deptInstituteLeaderIds",deptService.selectDeptIds(dept41));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkJobNoUnique(user))) {
            return AjaxResult.error("新增用户失败，员工编号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户失败，登录账号已存在");
        }
        user.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户信息")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        SysUser userRes = userService.selectUserByJobNo(user.getJobNo());
        
        int res = userService.checkUserNameUniqueEdit(user.getUserName());
        
        
       if (userRes!=null && userRes.getPhonenumber()!=null && !userRes.getPhonenumber().equals(user.getPhonenumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户失败，手机号码已存在");
        }
       
       if(userRes !=null && userRes.getUserName()!=null) {
    	   if(!userRes.getUserName().equals(user.getUserName()) && res>=1) {
    		   return AjaxResult.error("修改用户失败，登录账号已存在");
    	   }
    	   if(userRes.getUserName().equals(user.getUserName()) && res>=2) {
    		   return AjaxResult.error("修改用户失败，登录账号已存在");
    	   }
       }else {
    	   if(res>=1) {
    		   return AjaxResult.error("修改用户失败，登录账号已存在");
    	   }
       }
        user.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
       if(user.getPassword()!=null && !"".equals(user.getPassword())) {
    	   user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
       }
        
        return toAjax(userService.updateUser(user,false));
    }
    
    /**
     * 修改密码
     */
    @ApiOperation("修改密码")
    @PostMapping("/editPassword")
    public AjaxResult editPassword(String phonenumber, String password, String code, String uuid) {
    	return toAjax(userService.editUserPwd(phonenumber, password, code, uuid));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable String[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        return toAjax(userService.updateUserStatus(user));
    }
    
    /**
     * 判断用户是否存在
     */
    @ApiOperation("判断用户是否存在")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @GetMapping("/checkUser/{jobNo}")
    public AjaxResult checkUser(@PathVariable("jobNo") String jobNo) {
    	SysUser user = new SysUser();
    	user.setJobNo(jobNo);
    	String res = userService.checkJobNoUnique(user);
    	if(UserConstants.NOT_UNIQUE.equals(res)) {
    		return AjaxResult.success("0");
    	}else {
    		return AjaxResult.success("1");
    	}
    }
    
    /**
     * 新增用户
     */
    @ApiOperation("查询用户状态")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/getUserStatus")
    public AjaxResult getUserStatus(@RequestBody SysUser user) {
        return AjaxResult.success(userService.selectUserByJobNo(user.getJobNo()));
    }
    
    
}